package ensemble.samples.custom.sqlformat.javafx.util;

import java.io.File;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
import groovy.lang.GroovyObject;

/**
 * @author duanxq
 * @date 2021/8/11
 */
public class GroovyUtils {


    private static GroovyObject GROOVY_OBJECT;

    static  {
        try {
            String path = "/function/common.groovy";
            GROOVY_OBJECT =
                GroovyUtils.getGroovyObject(GroovyUtils.class.getResource(path).getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载Groovy文件，返回GroovyObject对象
     */
    private static GroovyObject getGroovyObject(File file) {
        GroovyObject groovyObject = null;
        try {
            GroovyClassLoader classLoader = new GroovyClassLoader(
                Thread.currentThread().getContextClassLoader());
            Class clazz = classLoader.parseClass(new GroovyCodeSource(file));
            groovyObject = (GroovyObject) clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return groovyObject;
    }

    private static GroovyObject getGroovyObject(String filePath) {
        return getGroovyObject(new File(filePath));
    }

    /**
     * 执行GroovyObject对象的方法
     */
    public static Object invokeMethod(String name, Object args) {
        return GROOVY_OBJECT.invokeMethod(name, args);
    }

}
